﻿Imports System.IO
Imports Training.Common

Partial Public Class AddQuiz
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub

    ''' <summary>
    ''' Upload file for cert image and add quiz data
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub UploadFile()
        Dim fn As String ' file name
        Dim ct As String ' file content
        Dim fz As String ' file size
        Dim fileUploaded As Boolean

        ' initial value of fileUploaded
        fileUploaded = False

        fn = fuCert.PostedFile.FileName
        ct = fuCert.PostedFile.ContentType
        fz = fuCert.PostedFile.ContentLength

        ' define path to upload folder
        Dim p As String
        p = Server.MapPath("../images")

        Try
            ' upload the actual file
            fuCert.PostedFile.SaveAs(p & "\" & System.IO.Path.GetFileName(fn.ToString()))
            ' set fileUploaded
            fileUploaded = True

            ' proceed with data insert if upload was successful
            If fileUploaded Then
                ' get file type and path
                Dim typ As String ' type of file
                Dim pth As String ' path to file
                typ = Right(fn, 4)
                pth = System.IO.Path.GetFileName(fn.ToString())

                ' determine type
                Select Case typ
                    Case ".bmp"
                        typ = ".bmp"
                    Case Else
                        lblMsg.Text = "File type is not supported. Upload aborted."
                        Exit Sub
                End Select

                ' insert quiz information
                If AddNewQuiz(tbQuizName.Text, tbPass.Text, pth) = 0 Then
                    ' everything was successful
                    lblMsg.Text = "Quiz - " & tbQuizName.Text & " - Added, Image Uploaded<br />File Name: " & fn & "<br />File Type: " & ct & "<br />File Size: " & fz
                Else
                    lblMsg.Text = "Error inserting data."
                End If
            Else
                ' upload failed, notify user
                lblMsg.Text = "File was not uploaded. Insert aborted."
            End If
        Catch ex As Exception
            ' also log error here
            lblMsg.Text = ex.ToString
        End Try

    End Sub

    ''' <summary>
    ''' Add Quiz Button click event
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        UploadFile()
    End Sub
End Class